# -*- coding: utf-8 -*-
"""
    管理员
"""
import os
import uuid
from flask import render_template, flash, redirect, url_for, request, current_app, Blueprint, send_from_directory
from flask_login import login_required, current_user

from main.extensions import db
from main.forms import SettingForm,ProjectForm,TaskForm
from main.utils import redirect_back
from main.models import Task,Project
from main import app
from werkzeug import secure_filename
@app.route('/setting', methods=['GET', 'POST'])
@login_required
def setting():
    form = SettingForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.username=form.username.data
        db.session.commit()
        flash('Setting updated.', 'success')
        return redirect(url_for('blog.index'))
    form.name.data = current_user.name
    form.username.data = current_user.username
    return render_template('admin/settings.html', form=form)
@app.route('/file/new', methods=['GET', 'POST'])
@login_required
def new_file():
    if request.method == 'POST':
        f = request.files.get('file')
        f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
    return render_template('admin/new_file.html')
@app.route('/task/new', methods=['GET', 'POST'])
@login_required
def new_task():
    form = TaskForm()
    if form.validate_on_submit():
        id=form.batch.data
        name=form.name.data
        batch = form.batch.data
        ttype = form.ttype.data
        status = form.status.data
        publisher = form.publisher.data
        contact = form.contact.data
        nature = form.nature.data
        start_time = form.start_time.data
        project_id = form.project_name.data
        uid=uuid.uuid4()
        f=form.pic_upload.data
        filename=secure_filename(f.filename)
        print(filename)
        print(app.config['UPLOADED_PATH'][0])
        uploadpath=os.path.join(app.config['UPLOADED_PATH'][0],filename)
        f.save(uploadpath)
        pic_path=uploadpath
        flash('照片已上传')
        f_v=form.video_upload.data
        filename=secure_filename(f_v.filename)
        uploadpath=os.path.join(app.config['UPLOADED_PATH'][0],filename)
        f_v.save(uploadpath)
        video_path=uploadpath
        flash('视频已上传')
        task = Task(name=name,batch=batch, ttype=ttype, status=status,publisher=publisher,contact=contact,nature=nature,\
        cost=4,start_time=start_time,project_id=project_id,uid=uid,pics=pic_path,videos=video_path)
        # same with:
        # category_id = form.category.data
        # post = Post(title=title, body=body, category_id=category_id)
        db.session.add(task)
        # db.session.flush()
        # nid=task.id
        db.session.commit()
        flash('任务成果创建成功.', 'success')
        return redirect(url_for('index', task_id=task.id))
    return render_template('admin/new_task.html', form=form)